package com.lagou.web.servlet;

import com.lagou.base.Constants;
import com.lagou.pojo.Course;
import com.lagou.service.CourseService;
import com.lagou.service.impl.CourseServiceImpl;
import com.lagou.utils.DateUtils;
import com.lagou.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/courseSalesInfo")
public class CourseSalesInfoServlet extends HttpServlet {
    /**
     * 保存课程营销的信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Course course = new Course();
            Map<String,Object> map = new HashMap<>();
            // 创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            // 解析request对象，获取表单项集合
            List<FileItem> list = fileUpload.parseRequest(req);
            for (FileItem fileItem : list) {
                boolean formField = fileItem.isFormField();
                if(formField){
                    // 是普通表单项，获取表单项中的数据，保存到map
                    String fieldName = fileItem.getFieldName();
                    String value = fileItem.getString("utf-8");
                    // 使用map收集数据
                    map.put(fieldName,value);
                }else{
                    // 文件上传项
                    // 获取文件名
                    String name = fileItem.getName();
                    // 拼接新的文件名 使用UUID保证不重复
                    String newFileName = UUIDUtils.getUUID()+"_"+name;
                    // 获取输入流
                    InputStream inputStream = fileItem.getInputStream();
                    // 获取项目的运行目录
                    String realPath = this.getServletContext().getRealPath("/");
                    // 截取到webapps的路径
                    String hello_work_war = realPath.substring(0, realPath.indexOf("hello_work_war"));
                    // 获取输出流
                    FileOutputStream fileOutputStream = new FileOutputStream(hello_work_war+"/upload/" + newFileName);
                    IOUtils.copy(inputStream,fileOutputStream);
                    fileOutputStream.close();
                    inputStream.close();
                    // 讲图片路径信息进行保存
                    map.put("course_img_url", Constants.LOCAL_URL+"/upload/" + newFileName);
                }
            }
            // 使用BeanUtils 将map中的数据封装到course对象
            BeanUtils.populate(course,map);
            String dateFormart = DateUtils.getDateFormart();
            CourseService service = new CourseServiceImpl();
            if(map.get("id")!=null){
                // 修改操作
                course.setUpdate_time(dateFormart);
                String result = service.updateCourseSalesInfo(course);
                resp.getWriter().print(result);
            }else{
                // 新建操作
                // 补全信息

                course.setCreate_time(dateFormart);
                course.setUpdate_time(dateFormart);
                course.setStatus(1);

                // 业务处理

                String salesInfo = service.saveCourseSalesInfo(course);
                resp.getWriter().print(salesInfo);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
